<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="款式" prop="type">
            <el-select v-model="queryParams.type" filterable clearable placeholder="请选择款式" style="width: 240px">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="面皮" prop="mianpi">
            <el-select v-model="queryParams.mianpi" filterable clearable placeholder="请选择面皮" style="width: 240px">
              <el-option v-for="item in leatherOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="面皮颜色" prop="mpColor">
            <el-select v-model="queryParams.mpColor" filterable clearable placeholder="请选择面皮颜色" style="width: 240px">
              <el-option v-for="item in colorOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="面皮材质" prop="mpCaizhi">
            <el-input v-model="queryParams.mpCaizhi" placeholder="请输入面皮材质" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="底皮" prop="dipi">
            <el-select v-model="queryParams.dipi" filterable clearable placeholder="请选择底皮" style="width: 240px">
              <el-option v-for="item in leatherOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="底皮颜色" prop="dpColor">
            <el-select v-model="queryParams.dpColor" filterable clearable placeholder="请选择底皮颜色" style="width: 240px">
              <el-option v-for="item in colorOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="底皮材质" prop="dpCaizhi">
            <el-input v-model="queryParams.dpCaizhi" placeholder="请输入底皮材质" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="尾形" prop="tailType">
            <el-select v-model="queryParams.tailType" placeholder="请选择尾形" clearable style="width: 240px">
              <el-option v-for="dict in business_tail_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:beltBody:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:beltBody:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:beltBody:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:beltBody:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="beltBodyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column label="样图" align="center" prop="imgMap" min-width="180">
          <template #default="scope">
            <el-image
              v-for="(item, key) in scope.row.imgMap"
              :src="item"
              :key="key"
              fit="contain"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[item]"
              :teleported="true"
              :preview-teleported="true"
              :hide-on-click-modal="true"
              style="margin-right: 5px; width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="款式" align="center" prop="type" min-width="100">
          <template #default="scope">
            <span>{{ typeOptions.find(item => item.value === scope.row.type)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面皮" align="center" prop="mianpi" min-width="100">
          <template #default="scope">
            <span>{{ leatherOptions.find(item => item.value === scope.row.mianpi)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面皮颜色" align="center" prop="mpColor" min-width="80">
          <template #default="scope">
            <span>{{ colorOptions.find(item => item.value === scope.row.mpColor)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面皮材质" align="center" prop="mpCaizhi" min-width="100" />
        <el-table-column label="底皮" align="center" prop="dipi" min-width="100">
          <template #default="scope">
            <span>{{ leatherOptions.find(item => item.value === scope.row.dipi)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="底皮颜色" align="center" prop="dpColor">
          <template #default="scope">
            <span>{{ colorOptions.find(item => item.value === scope.row.dpColor)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="底皮材质" align="center" prop="dpCaizhi" />
        <el-table-column label="尾形" align="center" prop="tailType" width="60">
          <template #default="scope">
            <span>{{ business_tail_type.find(item => item.value === scope.row.tailType)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="宽度（mm）" align="center" prop="width" width="100" />
        <el-table-column label="厚度（mm）" align="center" prop="thickness" width="100" />
        <el-table-column label="成本价" align="center" prop="costPrice" width="70" />
        <el-table-column label="状态" align="center" prop="status" width="70">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:beltBody:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:beltBody:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改基本信息-带身管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="beltBodyFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="款式" prop="width">
          <el-select v-model="form.type" filterable clearable placeholder="请选择款式" style="width: 100%">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="面皮" prop="mianpi">
          <el-select v-model="form.mianpi" filterable clearable placeholder="请选择面皮" style="width: 100%">
            <el-option v-for="item in leatherOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="面皮颜色" prop="mpColor">
          <el-select v-model="form.mpColor" filterable clearable placeholder="请选择面皮颜色" style="width: 100%">
            <el-option v-for="item in colorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="面皮材质" prop="mpCaizhi">
          <el-input v-model="form.mpCaizhi" placeholder="请输入面皮材质" />
        </el-form-item>
        <el-form-item label="底皮" prop="dipi">
          <el-select v-model="form.dipi" filterable clearable placeholder="请选择面皮" style="width: 100%">
            <el-option v-for="item in leatherOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="底皮颜色" prop="dpColor">
          <el-select v-model="form.dpColor" filterable clearable placeholder="请选择底皮颜色" style="width: 100%">
            <el-option v-for="item in colorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="底皮材质" prop="dpCaizhi">
          <el-input v-model="form.dpCaizhi" placeholder="请输入底皮材质" />
        </el-form-item>
        <el-form-item label="尾形" prop="tailType">
          <el-select v-model="form.tailType" placeholder="请选择尾形" clearable style="width: 100%">
            <el-option v-for="dict in business_tail_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="宽度（mm）" prop="width">
          <el-input v-model="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="厚度（mm）" prop="thickness">
          <el-input v-model="form.thickness" placeholder="请输入厚度" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="样图" prop="img">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            accept="image/*"
            :on-success="handleFileSuccess"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :auto-upload="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BeltBody" lang="ts">


import { globalHeaders, uploadFilePath } from "@/utils/request";

const { proxy } = getCurrentInstance() as ComponentInternalInstance
import { listBeltBody, getBeltBody, delBeltBody, addBeltBody, updateBeltBody } from '@/api/business/beltBody';
import { BeltBodyVO, BeltBodyQuery, BeltBodyForm } from '@/api/business/beltBody/types';
import { listColor } from "@/api/business/color";
import { listStyle } from "@/api/business/style"
import { listLeather } from "@/api/business/leather"
import to from "await-to-js";
const { business_tail_type } = toRefs<any>(proxy?.useDict('business_tail_type'));
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'


const beltBodyList = ref<BeltBodyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const beltBodyFormRef = ref<ElFormInstance>();
let imgArray = []


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const colorOptions =  ref<Array<{value: string|number, label: string}>>([])
const typeOptions = ref<Array<{value: string|number, label: string}>>([])
const leatherOptions = ref<Array<{value: string|number, label: string}>>([])

const initFormData: BeltBodyForm = {
  id: undefined,
  width: undefined,
  thickness: undefined,
  type: undefined,
  mianpi: undefined,
  mpColor: undefined,
  mpCaizhi: undefined,
  dipi: undefined,
  dpColor: undefined,
  dpCaizhi: undefined,
  tailType: undefined,
  img: undefined,
  costPrice: undefined,
  status: undefined,
}
const data = reactive<PageData<BeltBodyForm, BeltBodyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    width: undefined,
    thickness: undefined,
    type: undefined,
    mianpi: undefined,
    mpColor: undefined,
    mpCaizhi: undefined,
    dipi: undefined,
    dpColor: undefined,
    dpCaizhi: undefined,
    tailType: undefined,
    img: undefined,
    costPrice: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    width: [
      { required: true, message: "宽度不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "款式不能为空", trigger: "change" }
    ],
    mianpi: [
      { required: true, message: "面皮不能为空", trigger: "blur" }
    ],
    mpColor: [
      { required: true, message: "面皮颜色不能为空", trigger: "blur" }
    ],
    dipi: [
      { required: true, message: "底皮不能为空", trigger: "blur" }
    ],
    dpColor: [
      { required: true, message: "底皮颜色不能为空", trigger: "blur" }
    ],

    tailType: [
      { required: true, message: "尾形不能为空", trigger: "change" }
    ],
    img: [
      { required: true, message: "样图不能为空", trigger: "blur" }
    ],
  }
});

//上传图片
let fileList=ref<UploadUserFile[]>()
//图片预览
const dialogImageUrl = ref('')
//图片上传dialog显式状态
const dialogVisible = ref(false)


const uploadRef = ref()

const upload = {
  //设置上传地址
  url: uploadFilePath,
  // 设置上传的请求头部
  headers: globalHeaders(),
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  //删除包含的id
  imgArray.splice(imgArray.indexOf(uploadFile.id), 1)
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleFileSuccess : UploadProps['onSuccess'] = (response, uploadFile) => {
  imgArray.push(response.data.ossId)

}

const { queryParams, form, rules } = toRefs(data);

/** 查询带身信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBeltBody(queryParams.value);
  beltBodyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  beltBodyFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BeltBodyVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  //fileList清空
  fileList = ref<UploadUserFile[]>()
  dialog.visible = true;
  dialog.title = "添加带身信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BeltBodyVO) => {
  reset();
  //上传框fileList清空
  fileList = ref<UploadUserFile[]>()
  const _id = row?.id || ids.value[0]
  const res = await getBeltBody(_id);
  imgArray = res.data.img.split(',')
  //上传框fileList赋值
  const att = []
  Object.entries(res.data.imgMap).forEach(e => {
    att.push({
      id: e[0],
      url: e[1]
    })

  })
  fileList.value = att
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改带身信息";
}

/** 提交按钮 */
const submitForm = () => {
  form.value.img = imgArray.join(',')
  beltBodyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBeltBody(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addBeltBody(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BeltBodyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除所选数据？').finally(() => loading.value = false);
  await delBeltBody(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/beltBody/export', {
    ...queryParams.value
  }, `带身信息_${new Date().getTime()}.xlsx`)
}

const getListColor = async () => {
  //获取状态为启用的颜色数据列表
  const res = await listColor({ "status": 0});
  colorOptions.value = res.rows.map(item => {
    return {
      value: item.id,
      label: item.name
    }
  })
}

const getListStyle = async () => {
  //获取款式数据列表
  const res = await listStyle({ "status": 0});
  typeOptions.value = res.rows.map(item => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
const getListLeather = async () => {
  //获取皮料数据列表
  const res = await listLeather({ "status": 0 });
  leatherOptions.value = res.rows.map(item => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
const handleStatusChange = async (row: BeltBodyVO) => {
  let text = row.status === "0" ? "启用" : "禁用";
  const [err] = await to(proxy?.$modal.confirm("确认要" + text + "吗？") as Promise<any>);
  if (err) {
    row.status = row.status === "0" ? "1" : "0";
  } else {
    await updateBeltBody(row)
    proxy?.$modal.msgSuccess(text + "成功");
  }
};

onMounted(() => {
  getList();
  //获取款式list
  getListStyle()
  //获取颜色list
  getListColor()
  //获取皮料list
  getListLeather()

});
</script>
